package com.venus.lms.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.venus.lms.mapper.UserMapper;
import com.venus.lms.pojo.User;
import com.venus.lms.utils.RegexUtils;
import com.venus.lms.utils.Result;
import com.venus.lms.utils.SmsUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 忘记密码时，重置密码控制器
 *
 * @author DQM
 */
@RestController
@RequestMapping("/forget")
public class ForgetController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserMapper userMapper;

    /**
     * 重置密码时，发送短信验证码
     */
    @GetMapping("/getcode")
    public Result<?> getcode(@RequestParam String username) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            return Result.error("-1", "用户名不存在");
        }
        String phone = user.getPhone();
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.error("-1", "手机号错误或未绑定手机号");
        }
        String code = RandomUtil.randomNumbers(6);  //六位随机验证码
        stringRedisTemplate.opsForValue().set(phone, code, 5L, TimeUnit.MINUTES);  //将验证码存入redis，5分钟有效
        try {
            SmsUtils.sendSms(phone, code);   //阿里云短信服务发送验证码
        } catch (ClientException e) {
            return Result.error("-1", "验证码服务异常");
        }
        return Result.success();
    }

    /**
     * 重置密码提交功能
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername, user.getUsername());
        User user1 = userMapper.selectOne(wrapper);
        String phone = user1.getPhone();
        System.out.println(phone);
        String code = stringRedisTemplate.opsForValue().get(phone);  //从redis中取出验证码
        if (code == null) {
            return Result.error("-1", "请先获取验证码");
        }
        if (user.getCode().equals(code)) {
            user.setId(user1.getId());
            //修改为新的密码
            userMapper.updateById(user);
            //redis中删除短信验证码
            stringRedisTemplate.delete(phone);
            return Result.success();
        }
        return Result.error("-1", "验证码错误");
    }
}
